<template>
  <div id="assignMenu">
    <h3>分配菜单</h3>
    <el-input
        placeholder="输入关键字进行过滤"
        v-model="filterText">
    </el-input>
    <el-tree
        class="filter-tree"
        :data="menuList"
        :props="defaultProps"
        :default-checked-keys="menuByRid"
        :filter-node-method="filterNode"
        ref="tree"
        node-key="id"
        show-checkbox
        @check-change="handleCheckChange">
    </el-tree>
    <div class="form-actions" style="display: flex; justify-content: flex-end; align-items: center; margin-top: 20px;">
      <el-button @click="closeBtn">返回</el-button>
      <el-button type="primary" @click="assignMenu">确 定</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "AssignMenu",
  data() {
    return {
      filterText: '',
      //当前角色菜单id列表
      menuByRid: [],
      //角色Id
      roleId: "",
      //菜单列表
      menuList: [],
      defaultProps: {
        children: 'children',  // 告诉树组件，子节点数据在节点的哪个属性中
        label: 'name',  // 告诉树组件，节点的标签显示在哪个属性中
      },
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    //分配确定
    async assignMenu() {
      const checkedKeys = this.$refs.tree.getCheckedKeys();
      if (checkedKeys.length === 0)
        return this.$message.warning("请给角色选中菜单！")
      const { data: res } = await this.$http.post(`/backRoleMenu/updateRoleMenuByRid/${this.roleId}`,checkedKeys);
      this.$message.success(res);
      this.$router.push("/role")
    },
    //返回
    closeBtn() {
      this.$router.push('/role')
    },
    //过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //菜单列表
    async queryBackMenuList() {
      const { data: res } = await this.$http.post(`/backMenu/queryBackMenuList`);
      this.menuList = res;
    },
    //当前角色的菜单id
    async queryMenuIdByRoleId() {
      const { data: res } = await this.$http.post(`/backRoleMenu/queryMenuIdByRoleId/${this.roleId}`);
      this.menuByRid = res;
    },

    handleCheckChange(data, checked, indeterminate) {
      console.log('22',data, checked, indeterminate);
    },


  },

  created() {
    //角色id
    this.roleId = this.$route.query.id;

    //当前角色的菜单id
    this.queryMenuIdByRoleId();
    //菜单列表
    this.queryBackMenuList();

  }
}
</script>

<style scoped>

</style>